/*****************************************************************************************
 **  Author:jxx 2022
 **  QQ:283591387
 **完整文档见：http://v2.volcore.xyz/document/api 【代码生成页面ViewGrid】
 **常用示例见：http://v2.volcore.xyz/document/vueDev
 **后台操作见：http://v2.volcore.xyz/document/netCoreDev
 *****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
import modelHeader from "../produce_use/produceUse.vue"
import modelBody from "../../inventoryinfo/goods_inventory_warehouse_xm/goodsInventoryWarehouse_xm.vue"
// import modelFooter from "../produce_use_mx/produceUseMx.vue"
import modelFooter from "../q_produce_use_kcmx/produceUseKcmx.vue"
import gridHeader from "@/components/print/selectTemplet.vue"
import {
  ElMessage
} from 'element-plus'
import {
  mapMutations
} from "vuex";
let extension = {
  components: {
    //查询界面扩展组件
    gridHeader,
    gridBody: '',
    gridFooter: '',
    //新建、编辑弹出框扩展组件
    modelHeader: modelHeader,
    modelBody: modelBody,
    modelFooter: modelFooter
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: {
    view: [],
    box: [],
    detail: []
  }, //扩展的按钮
  methods: {
    ...mapMutations(
      ("salesContractMX", ["storeRemoveForm", "storeChangeForm"])
    ),
    //下面这些方法可以保留也可以删除
    async onInit() {
      this.queryFields = ["Proposer", "CreateDate"]
      let startTime = await this.base.getOneWeekAgoDate()
      let endTime = await this.base.getDate(false) + " 23:59:59"
      this.searchFormFields.CreateDate = [startTime, endTime]
      this.detailOptions.textInline = false
      this.textInline = false
      this.editFormOptions.forEach(option => {
        option.forEach(item => {
          if (item.field == "WHSE_no" || item.field == "WHSE_jg") {
            item.hidden = true
          }
          if (item.field == "Produce_use_voucher_sub") {
            // item.remote = true
            item.extra = {
              icon: "el-icon-zoom-in",
              text: "选择领用单",
              style: "color:#3a8ee6;font-size:13px;cursor:default",
              click: () => {
                this.$store.commit("setTabelText", true)
                this.$refs.modelHeader.open()

              }
            }
          }
        })
      })
      if (this.$route.path == "/q_produce_return" && JSON.stringify(this.$route.query) != '{}') {
        console.log("触发查询")
        await this.base.setSearchParamFn(this)
        // this.searchFormFields.Voucher_sub = null
        // this.searchFormFields.Goods_sub = null
        // this.searchFormFields.Goods_name = null
        // this.searchFormFields.Proposer = null
        // this.searchFormFields.AuditStatus = null
        // this.searchFormFields.CreateDate = [null, null]
        // const selectList = ['AuditStatus','CreateDate',]
        // this.searchFormOptions.forEach(item => {
        //   item.forEach(x => {
        //     if (selectList.includes(x.field)) {
        //       x.onChange = (v) => {
        //         this.$route.query = {}
        //       }
        //     }
        //   })
        // })
        setTimeout(() => {
          this.refresh()
        })
      }
    },
    onInited() {
      // this.setFiexdSearchForm(true);
      // this.buttons.forEach(item => {
      //   if (item.name == "高级查询") {
      //     item.hidden = true
      //   }
      // })
      let indexNum = this.detailOptions.buttons.findIndex(item => item.name == "添加行")
      if (indexNum != "-1") {
        this.detailOptions.buttons.splice(indexNum, 1)
      }
      this.detailOptions.buttons.unshift({
        name: "退回",
        icon: 'el-icon-plus',
        type: 'primary',
        plain: true,
        onClick: function () {
          if (!this.editFormFields.Produce_use_voucher_sub) {
            this.base.ElMessageFn("请先选择领用单")
            return
          }
          if (this.rowschild) {
            this.rowschild.click()
          }
          let form = {
            领用单号: this.editFormFields.Produce_use_voucher_sub,
          }
          this.$store.commit("setTabelText", true)
          this.storeChangeForm(form);
          this.$refs.modelFooter.open(this.editFormFields.Produce_use_voucher_sub)
        }
      })

      this.detailOptions.buttons.unshift({
        name: "增加", //按钮名称
        icon: 'el-icon-plus', //按钮图标，参照iview图标
        type: 'primary',
        plain: true,
        onClick: function () { //触发事件

          if (!this.editFormFields.Produce_use_voucher_sub) {
            this.base.ElMessageFn("请先选择领用单")
            return
          }
          if (this.rowschild) {
            this.rowschild.click()
          }
          this.$store.commit("setTabelText", true)
          this.$refs.modelBody.open(this.editFormFields.WHSE_no, this.editFormFields.WHSE_jg)
        }
      })


      this.detailOptions.beginEdit = (row, column, index) => {
        if (this.$route.path != "/q_produce_return" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
          return false
        }
        // this.detailOptions.columns.forEach(item => {
        //   if (item.field == "WHSE_name") {

        //     let selectUrl = `api/q_warehouse_locationList/getgoodslocation?bm=${row.Goods_sub}`
        //     item.bind.data.forEach(d => {
        //       d.hidden = true
        //     })
        //     this.http.post(selectUrl, {}, "").then(reslut => {
        //       item.bind.data.forEach(d => {
        //         d.hidden = true
        //       })
        //       item.bind.data.forEach(d => {
        //         reslut.rows.forEach(j => {
        //           if (d.key == j.WHSE_no) {
        //             d.hidden = false
        //           }
        //         })
        //       })
        //     })

        //     item.onChange = (column, row, tableData) => {
        //       if (column.Goods_num) {
        //         this.getInventoryNum(column, column.Goods_num)
        //       }
        //     }
        //   }
        // })

        let rows = document.querySelectorAll(".grid-detail .el-table__body .el-table__row")
        setTimeout(() => {
          this.rowschild = rows[0].childNodes[2]
          let testInputDom = rows[index].querySelectorAll("td")[6].querySelector("input")
          testInputDom.addEventListener("keyup", (e) => {

            //在这里去请求判断库存数量
            if (+e.target.value) {
              try {
                if ( +e.target.value < 0) {
                  this.base.ElMessageFn("调整数量需要大于零")
                // } else if (row.AvailableQuantity < Math.abs(+e.target.value)) {
                } else if (row.AvailableQuantity < +e.target.value) {
                  try {
                    this.base.ElMessageFn(`调整数量大于可用数量`)
                  } catch (error) {
                    console.error(error);
                  }
                } else {
                  ElMessage.closeAll()
                }
              } catch (error) {
                console.error(error);
              }
              // if (row.WHSE_name) {
              //   let url = `api/q_goods_inventory/getgoodsquantity?kw=${row.WHSE_name}&bm=${row.Goods_sub}`
              //   this.http.post(url, {}, "").then(({ rows }) => {
              //     try {

              //       if (typeof rows[0] == "object") {
              //         let data = rows[0]
              //         let off = +data.goods_inventory_quantity < + e.target.value || e.target.value == undefined
              //         if (off) {
              //           this.$message.error("此商品在该库位实际库存" + data.goods_inventory_quantity)
              //           e.target.blur()
              //           setTimeout(() => {
              //             row.Goods_num = null
              //             setTimeout(() => {
              //               e.target.focus()
              //             }, 0)
              //           }, 0)
              //         }
              //       } else if (rows[0] == null) {
              //         this.$message.error("此商品在该库位暂无库存")
              //         e.target.blur()
              //         setTimeout(() => {
              //           row.Goods_num = null
              //           setTimeout(() => {
              //             e.target.focus()
              //           }, 0)
              //         }, 0)
              //       }
              //     } catch (error) {
              //       console.log("错误", error);
              //     }
              //   })
              // }
            } else {
              this.base.ElMessageFn("请输入数字")
            }
          })
        }, 0)
        return true
      }

    },
    async searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      if (this.$route.path == "/q_produce_return" && JSON.stringify(this.$route.query) != '{}') {
        await this.base.setSearchBefore(this, "Produce_return", param)
        // const sectionState = ["[null,null]",JSON.stringify(["",null]),JSON.stringify([null,""]),JSON.stringify(["",""])]
        // const dateState=sectionState.includes(JSON.stringify(this.searchFormFields.CreateDate))
        // if (this.searchFormFields.Voucher_sub ||this.searchFormFields.Goods_sub||this.searchFormFields.Goods_name||this.searchFormFields.Proposer||!dateState) {
        //    param.wheres=param.wheres.filter(item=>item.name!="Produce_return")
        //   this.$route.query = {}
        // }
      }
      return true;
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true;
    },
    delBefore(ids, rows) { //查询界面的表删除前 ids为删除的id数组,rows删除的行
      let auditStatus = rows.some(x => {
        return x.AuditStatus == 1
      });
      if (auditStatus) {
        this.base.ElMessageFn('不支持删除审核通过数据')
        return false;
      }
      return true;
    },
    async addBeforeAsync(formData) {
      this.storeRemoveForm()
      return this.testAdd(formData)
    },
    async updateBeforeAsync(formData) {
      this.storeRemoveForm()
      return this.testAdd(formData)
    },
    rowClick({
      row,
      column,
      event
    }) {
      //查询界面点击行事件
      this.$refs.table.$refs.table.toggleRowSelection(row);
    },

    detailRowClick({
      row,
      column,
      event
    }) {
      this.$refs.detail.$refs.table.toggleRowSelection(row);
      if (this.$route.path != "/q_produce_return" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
        return
      }
      if (column.property == "Goods_num" || column.property == "Remark") {
        let dom = event.target
        if (dom.nodeName != "SPAN") {
          setTimeout(() => {
            let inpDom = dom.querySelector("input")
            inpDom.focus()
          }, 0)
        }
      }
    },
    onModelClose(iconClick) {
      //iconClick=true为点击左中上角X触发的关闭事件
      //如果返回 false不会关闭弹出框 
      //return false;
      this.storeRemoveForm()
      this.$store.commit("setTabelText", true)
      this.boxModel = false;
    },
    async modelOpenBefore(row) {
      this.$store.commit("setTabelText", false)
      this.CreateUserBoole = row.CreateID == this.$store.state.userID
      this.rowAuditStatus = await row.AuditStatus
      if (JSON.stringify(row) == "{}") {
        this.rowAuditStatus = 0
        this.CreateUserBoole = true
      }
      if (this.$route.path != "/q_produce_return" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
        this.boxButtons[0].hidden = true
        this.detailOptions.buttons.forEach(item => {
          if (item.name != "导出" && item.name != "刷新") {
            item.hidden = true
          }
        })
      } else {
        this.boxButtons[0].hidden = false
        this.detailOptions.buttons.forEach(item => item.hidden = false)
      }
    },
    modelOpenAfter(row) {
      this.rowschild = null
      this.editFormFields.Production_state = 1
      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          if (x.field == "Produce_use" || x.field == "Goods_name" || x.field == "Production_state") {
            try {
              x.hidden = true
            } catch (error) {
              console.error(error);
            }
          }
          if (x.field == "Voucher_sub" || x.field == "Produce_use_voucher_sub" || x.field == "Goods_sub" || x.field == "Proposer" || this.$route.path != "/q_produce_return" || this.rowAuditStatus != 0) {
            x.disabled = true
          } else {
            x.disabled = false
          }
          if (x.field == "Produce_use_voucher_sub") {
            if (this.currentAction == 'Add') {
              x.extra = {
                icon: "el-icon-zoom-in",
                text: "选择领用单",
                style: "color:#3a8ee6;font-size:13px;cursor:default",
                click: () => {
                  this.$store.commit("setTabelText", true)
                  this.$refs.modelHeader.open()

                }
              }
            } else {
              x.extra = null
            }
          }
        })
      })
    },
    async getSummary(formData) {
      let detailRowData = this.$refs.detail.rowData
      let num = 0
      let summaryPrc = 0
      let summaryNum = 0
      await detailRowData.forEach(item => {
        item.Produce_use = this.editFormFields.Produce_use
        summaryPrc += item.Goods_price * item.Goods_num
        summaryNum += +item.Goods_num

        if (item.Goods_sub && item.Goods_name && item.Goods_num && item.WHSE_name) num++
        if (item.Type == 0 && item.Goods_num > 0) {
          item.Goods_num = -item.Goods_num
        } else if (item.Type == 1 && item.Goods_num < 0) {
          item.Goods_num = Math.abs(+item.Goods_num)
        }
      })
      if (detailRowData.length == num) {
        return true
      } else {
        this.$message.error("请正确选择商品")
        return false
      }
    },
    testAdd(formData) {
      if (!this.$refs.detail.rowData.length) {
        this.base.ElMessageFn('明细表不可为空', "error")
        return false
      }
      let boole2 = formData.detailData.some(item => +item.Goods_num === 0)
      if (boole2) {
        this.base.ElMessageFn("明细表中调整数量不可为零")
        return false;
      }
      let boole = formData.detailData.some(item => item.Goods_num == "" || item.Goods_num == null || item.Goods_num == undefined)
      if (boole) {
        this.base.ElMessageFn("明细表中请填写调整数量")
        return false;
      }
      let boole3 = formData.detailData.every(item => +item.Goods_num > 0 && +item.Goods_num)
      if (!boole3) {
        this.base.ElMessageFn("明细表中调整数量请填写有效正数")
        return false;
      }
      let boole4 = formData.detailData.some(item => +item.Goods_num > +item.AvailableQuantity)
      if (boole4) {
        this.base.ElMessageFn("明细表中调整数量大于可用数量")
        return false;
      }
      return true
    },
    async getInventoryNum(rowObj, val) {
      let url = `api/q_goods_inventory/getgoodsquantity?kw=${rowObj.WHSE_name}&bm=${rowObj.Goods_sub}`
      await this.http.post(url, {}, "").then(({
        rows
      }) => {
        try {
          if (typeof rows[0] == "object") {
            let data = rows[0]
            let off = +data.goods_inventory_quantity < +val || val == undefined
            if (off) {
              this.$message.error("此商品在该库位实际库存" + data.goods_inventory_quantity)
              setTimeout(() => {
                rowObj.Goods_num = null
              }, 0)
            }
          } else if (rows[0] == null) {
            this.$message.error("此商品在该库位暂无库存")
            rowObj.Goods_num = null
          }
        } catch (error) {
          console.log("错误", error);
        }

      })
    },
  }
};
export default extension;